<template>
  <el-container
    class="container"
    direction="horizontal"
  >
    <el-container class="left">
      <el-header class="left-title">
        <el-row style="width: 100%; height: 100%">
          <el-col :span="12" style="height: 100%; display: flex; justify-items: left;align-items: center">
            <span>部门负责人</span>
            <el-checkbox
              v-model="showFilterDept"
              style="margin-left: 20px"
            >显示统计</el-checkbox>
          </el-col>
          <el-col :span="12" style="height: 100%; display: flex; justify-content: right; align-items: center">
            <el-button
              size="small "
              type="primary"
              style="margin-left: 20px"
              :loading="initLoading"
              @click="initData"
            >初始化数据</el-button>
          </el-col>
        </el-row>
        <!--        <el-input v-model="filterDeptText" placeholder="请输入搜索部门"></el-input>-->
      </el-header>
      <el-main class="left-content">
        <el-table
          ref="deptTable"
          v-loading="deptLoading"
          :data="filterDeptData"
          row-key="id"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          highlight-current-row
          style="width: 100%"
          height="100%"
          @current-change="rowChangeHandle"
        >
          <el-table-column
            prop="deptName"
            header-align="center"
            label="名称"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="deptName"
            header-align="center"
            label="简称"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div v-if="scope.$index === currentDeptEditRowIndex">
                <el-input v-model="currentEditDeptData.deptShortName" placeholder="请输入部门简称" />
              </div>
              <span v-else>{{ scope.row.deptShortName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="负责人"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div v-if="scope.$index === currentDeptEditRowIndex">
                <el-tag
                  size="medium"
                  style="cursor: pointer"
                  @click.stop="principalClickHandle(scope.row)"
                >
                  {{ currentEditDeptData.principal }}
                </el-tag>
              </div>
              <span v-else>{{ scope.row.principal }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="是否统计"
            header-align="center"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="scope.$index === currentDeptEditRowIndex"
                v-model="currentEditDeptData.isDelete"
                active-color="#409EFF"
                inactive-color="#c8c9cc"
                :active-value="0"
                :inactive-value="1"
              />
              <span v-else>{{ scope.row.isDelete === 0 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            label="操作"
            width="60"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.$index === currentDeptEditRowIndex"
                type="text"
                size="small"
                @click.stop="saveDeptRow(scope.row, scope.$index)"
              >保存</el-button>
              <el-button
                v-else
                type="text"
                size="small"
                @click.stop="deptRowEdit(scope.row, scope.$index)"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <el-container class="right">
      <el-header class="right-title">
        <el-row style="width: 100%; height: 100%">
          <el-col :span="12" style="height: 100%; display: flex; justify-items: left;align-items: center">
            <span>项目</span>
            <el-checkbox
              v-model="showFilterProject"
              style="margin-left: 20px"
            >显示统计</el-checkbox>
          </el-col>
          <el-col :span="12" style="height: 100%; display: flex; justify-content: right; align-items: center">
            <el-button
              size="small "
              type="primary"
              style="margin-left: 20px"
              :loading="initLoading"
              @click="updateProXMZ"
            >更新项目数据</el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-main class="right-content">
        <el-table
          v-loading="projectLoading"
          :data="filterProjectData"
          border
          style="width: 100%"
          height="100%"
        >
          <el-table-column
            prop="cflastname"
            label="名称"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="director"
            label="项目总"
            header-align="center"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.$index === currentProjectEditRowIndex">
                <el-tag
                  size="medium"
                  style="cursor: pointer"
                  @click="xmzClickHandle(scope.row)"
                >
                  {{ currentEditProjectData.xmzName }}
                </el-tag>
              </div>
              <span v-else>{{ scope.row.xmzName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="是否启用"
            header-align="center"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="scope.$index === currentProjectEditRowIndex"
                v-model="currentEditProjectData.isEnable"
                :active-value="1"
                :inactive-value="0"
                active-color="#409EFF"
                inactive-color="#c8c9cc"
              />
              <span v-else>{{ scope.row.isEnable === 1 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            label="未启用原因"
            min-width="250"
          >
            <template slot-scope="scope">
              <div v-if="currentEditProjectData.isEnable === 0 && scope.$index === currentProjectEditRowIndex">
                <el-input v-model="currentEditProjectData.reason" placeholder="请输入未启用原因" />
              </div>
              <span v-else>{{ scope.row.reason }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="是否统计"
            header-align="center"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="scope.$index === currentProjectEditRowIndex"
                v-model="currentEditProjectData.isDelete"
                active-color="#409EFF"
                inactive-color="#c8c9cc"
                :active-value="0"
                :inactive-value="1"
              />
              <span v-else>{{ scope.row.isDelete === 0 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            label="操作"
            width="60"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.$index === currentProjectEditRowIndex"
                type="text"
                size="small"
                @click.stop="saveProjectRow(scope.row, scope.$index)"
              >保存</el-button>
              <el-button
                v-else
                type="text"
                size="small"
                @click.stop="projectRowEdit(scope.row, scope.$index)"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <select-user-dialog
      :show.sync="showSelectUserVisible"
      :selected="selectedUser"
      @select="selectUserHandle"
    />
  </el-container>
</template>

<script>
import { queryDeptTree, queryProjectByDeptId, savePrincipalInfo, saveProInfo, updateProXMZInfo } from '@/api/baseManage/deptConfig'
import SelectUserDialog from '../../components/SelectUserDialog'
import { initData } from '../../../api/baseManage/deptConfig'
export default {
  name: 'DeptConfig',
  components: {
    SelectUserDialog
  },
  data() {
    return {
      deptData: [],
      projectData: [],
      showFilterDept: true,
      showFilterProject: true,
      deptLoading: false,
      projectLoading: false,
      initLoading: false,
      filterDeptText: '',
      showSelectUserVisible: false,
      selectedUser: [],
      editDeptVisible: false,
      editProjectVisible: false,
      currentDeptEditRowIndex: -1,
      currentProjectEditRowIndex: -1,
      currentEditDeptData: {},
      currentEditProjectData: {},
      /* 当前选中部门节点 */
      currentDeptId: ''
    }
  },
  computed: {
    filterDeptData() {
      const data = JSON.parse(JSON.stringify(this.deptData))
      function recuDeptData(arr) {
        if (arr.length > 0) {
          for (var i = 0; i < arr.length; i++) {
            var item = arr[i]
            if (item.isDelete === 0) {
              if ('children' in item && item.children.length > 0) {
                recuDeptData(item.children)
              }
            } else {
              arr.splice(i--, 1)
            }
          }
        }
      }
      if (this.showFilterDept) {
        // 一级过滤
        recuDeptData(data)
      }
      return data
    },
    filterProjectData() {
      let data = []
      if (this.showFilterProject) {
        if (this.projectData && this.projectData.length > 0) {
          this.projectData.forEach(item => {
            if (item.isDelete === 0) {
              const dept = { ...item }
              if ('children' in item && item.children.length > 0) {
                dept.children = [...item.children.filter(item => item.filter === 0)]
              }
              data.push(dept)
            }
          })
        }
      } else {
        data = [...this.projectData]
      }
      return data
    }
  },
  created() {
    this.queryDeptTree()
  },
  methods: {
    /**
     * 部门配置修改
     * @param row
     */
    saveDeptRow(row, index) {
      this.deptLoading = true
      row = Object.assign(row, this.currentEditDeptData)
      const data = { id: row.id, principal: row.principal, principalFids: row.principalFids, isDelete: row.isDelete, deptShortName: row.deptShortName }
      savePrincipalInfo(data).then(res => {
        if (res.code === 200) {
          if (data.isDelete === 1) {
            // this.projectData.filter(item => item.deptFid === data.isDelete).forEach(item => {
            //   item.isDelete = 1
            // })
          }
          this.$message.success('保存成功')
        }
        this.currentEditDeptData = {}
        this.currentDeptEditRowIndex = -1
        this.deptLoading = false
      })
    },
    /**
     * 部门配置修改
     * @param data
     */
    deptRowEdit(data, index) {
      if (this.currentDeptEditRowIndex > -1) {
        this.saveDeptRow({})
      }
      this.currentDeptEditRowIndex = index
      this.currentEditDeptData = { ...data }
    },
    /**
     * 部门配置修改
     * @param row
     */
    saveProjectRow(row, index) {
      this.projectLoading = true
      row = Object.assign(row, this.currentEditProjectData)
      const data = { id: row.id, xmzFids: row.xmzFids, xmzName: row.xmzName, isDelete: row.isDelete, isEnable: row.isEnable, reason: row.reason }
      saveProInfo(data).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功')
        }
        this.currentEditProjectData = {}
        this.currentProjectEditRowIndex = -1
        this.projectLoading = false
      })
    },
    /**
     * 部门配置修改
     * @param data
     */
    projectRowEdit(data, index) {
      if (this.currentProjectEditRowIndex > -1) {
        this.saveProjectRow({})
      }
      this.currentProjectEditRowIndex = index
      this.currentEditProjectData = { ...data }
    },
    /**
     * 负责人点击事件
     */
    principalClickHandle(data) {
      const selectedUser = []
      const principal = data.principal ? data.principal.split(',') : []
      const principalFids = data.principalFids ? data.principalFids.split(',') : []
      if (principal.length > 0 && principalFids.length > 0) {
        principalFids.forEach((item, index) => {
          selectedUser.push({ value: item, label: principal[index] })
        })
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    /**
     * 项目总点击事件
     * @param data
     */
    xmzClickHandle(data) {
      const selectedUser = []
      const xmzName = data.xmzName ? data.xmzName.split(',') : []
      const xmzFids = data.xmzFids ? data.xmzFids.split(',') : []
      if (xmzName.length > 0 && xmzFids.length > 0) {
        xmzFids.forEach((item, index) => {
          selectedUser.push({ value: item, label: xmzName[index] })
        })
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    /**
     * 部门列表行样式设置事件
     * @param currentRow 当前行
     * @param oldCurrentRow 之前的选择行
     */
    rowChangeHandle(currentRow, oldCurrentRow) {
      const deptId = currentRow.deptFid
      this.currentDeptId = deptId
      this.queryProjects(deptId)
    },
    /**
     * 查询部门树
     */
    queryDeptTree() {
      this.deptLoading = true
      queryDeptTree().then(res => {
        if (res.code === 200) {
          this.deptData = res.data
        }
        this.deptLoading = false
      })
    },
    /**
     * 查询项目集合
     * @param deptId 部门ID
     */
    queryProjects(deptId) {
      this.projectData = []
      this.projectLoading = true
      queryProjectByDeptId({ deptId }).then(res => {
        if (res.code === 200) {
          this.projectData = res.data
        }
        this.projectLoading = false
      })
    },
    /**
     * 选择用户后事件
     * @param selection 选择的数据
     */
    selectUserHandle(selection) {
      const principal = this.currentEditDeptData
      if (principal) {
        principal.principal = selection.map(item => item.label).join(',')
        principal.principalFids = selection.map(item => item.value).join(',')
      }
      const xmz = this.currentEditProjectData
      if (xmz) {
        xmz.xmzName = selection.map(item => item.label).join(',')
        xmz.xmzFids = selection.map(item => item.value).join(',')
      }
    },
    /**
     * 初始化数据
     */
    initData() {
      this.initLoading = true
      this.deptLoading = true
      this.projectLoading = true
      initData().then(res => {
        if (res.code) {
          this.$message.success('初始化数据成功')
        }
      }).finally(() => {
        this.initLoading = false
        this.deptLoading = false
        this.projectLoading = false
      })
    },
    /* 更新项目总数据 */
    updateProXMZ() {
      debugger
      updateProXMZInfo().then(res => {
        this.queryProjects(this.currentDeptId)
        this.$message.success('操作成功')
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.container {
  height: 100%;
  width: 100%;
  .left {
    .left-title {
      display: flex;
      justify-items: center;
      align-items: center;
    }
    .left-content {
      padding: 0 10px 10px;
    }
  }
  .right {
    width: 60%;
    border-left: 1px solid #dfe6ec;
    .right-title {
      display: flex;
      justify-items: center;
      align-items: center;
    }
    .right-content {
      padding: 0 10px 10px;
    }
  }
  /deep/ .expanded td:first-child {
    border-bottom: 1px solid #dfe6ec;
  }
}
</style>
